﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Bussiness.Data;
using Bussiness.Entities;
using Bussiness.Data.SqlClient;

namespace Mvc_Demo5.Controllers
{
    public class UsersController : Controller
    {
        //
        // GET: /Users/

        public ActionResult Index()
        {
            return View();
        }
      
        public ActionResult Users()
        {
            Bussiness.Entities.TList<Users> user = DataRepository.UsersProvider.GetAll();
            DataRepository.UsersProvider.DeepLoad(user, true, DeepLoadType.IncludeChildren, typeof(Group));
            var model = user;
            return View(model);
        }
        [HttpGet]
        public ActionResult EditUser(int id)
        {

            Bussiness.Entities.Users user= DataRepository.UsersProvider.GetById(id);
            DataRepository.UsersProvider.DeepLoad(user, true, DeepLoadType.IncludeChildren, typeof(Group));
            var model = user;
            ViewBag.GroupID = new SelectList(GetGroup(), "GroupID", "GroupName", model.GroupId);
            return View(model);
        }
        [HttpPost]
        public ActionResult EditUser(Users user)
        {
            var model=user;
            bool result = false;
            try
            {
                user.OriginalId = user.Id;
                result = DataRepository.UsersProvider.Update(user);
                model = DataRepository.UsersProvider.GetById(user.Id);
                if(result) ViewBag.result = "Update Sucessful";
                else
                    ViewBag.result = "Update Fail";
            }
            catch
            { 
                ViewBag.result = "Update Fail";
            }
            ViewBag.GroupID = new SelectList(GetGroup(), "GroupID", "GroupName", model.GroupId);
            return View(model);
        }
        [NonAction]
        public TList<Group> GetGroup()
        {
            return DataRepository.GroupProvider.GetAll();
        }
    }
}
